package com.sw.rpc.consumer;

import com.sw.rpc.service.JSONSerializer;
import com.sw.rpc.service.RpcEncoder;
import com.sw.rpc.service.RpcRequest;
import com.sw.rpc.service.zk.ServiceInstanceService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author sw
 * @project zdy-rpc
 * @description
 * @date 2020/5/15 13:38
 */
public class RpcConsumer {
    private static ExecutorService executor= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private static UserClientHandler userClientHandler;

    /**
     * 创建代理类的执行信息
     * @param serviceClass
     * @param rpc
     * @return
     */
    public Object createProxy(final Class<?> serviceClass,final RpcRequest rpc){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{serviceClass},new InvocationHandler(){
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(null==userClientHandler){
                    createClient();
                }
                //设置携带
                userClientHandler.setPara(rpc);
                /**
                 * 请求服务
                 */
                return executor.submit(userClientHandler).get();
            }

        });



    }

    public static void createClient() throws InterruptedException {
        userClientHandler = new UserClientHandler();

        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                       // pipeline.addLast(new StringEncoder());

                        pipeline.addLast(userClientHandler);
                    }
                });
        bootstrap.connect("localhost",8080).sync();

    }

    public void watchServerNode(){

    }


}
